<template>
  <el-container class="accounting-management">
    <!-- Main content area -->
    <el-main class="accounting-main">
      <!-- 顶部统计卡片 -->
      <el-row :gutter="16" class="stats-section">
        <el-col :xs="24" :sm="12" :md="6" v-for="(stat, index) in stats" :key="index">
          <el-card class="stat-card compact" :body-style="{ padding: '16px' }">
            <el-row justify="space-between" align="middle">
              <el-col :span="16">
                <div class="stat-content">
                  <h3 class="stat-title">{{ stat.title }}</h3>
                  <p :class="['stat-value', stat.type]">{{ stat.value }}</p>
                </div>
              </el-col>
              <el-col :span="8" class="stat-icon-col">
                <div :class="['stat-icon', stat.type]">
                  <el-icon size="20">
                    <component :is="stat.icon" />
                  </el-icon>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>

      <!-- 主要内容区域 -->
      <el-row class="main-content">
        <el-col :span="24">
          <div class="content-area">
            <el-row justify="space-between" align="middle" class="section-header">
              <el-col>
                <div class="action-buttons">
                  <el-button type="primary" @click="showAddTransactionModal = true" class="primary-action">
                    <el-icon><Plus /></el-icon>
                    <span class="button-text">记一笔</span>
                  </el-button>
                  <el-button type="info" plain @click="showAccountManagement = true">
                    <el-icon><Wallet /></el-icon>
                    <span class="button-text">账户管理</span>
                  </el-button>
                  <el-button type="info" plain @click="showCategoryManagement = true">
                    <el-icon><Document /></el-icon>
                    <span class="button-text">分类管理</span>
                  </el-button>
                  <el-button type="info" plain @click="showProjectManagement = true">
                    <el-icon><FolderOpened /></el-icon>
                    <span class="button-text">项目管理</span>
                  </el-button>
                </div>
              </el-col>
            </el-row>

                <!-- 筛选器 -->
                <el-row :gutter="16" class="filters">
                  <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item label="类型">
                      <el-select v-model="filters.transaction_type" @change="fetchTransactions" placeholder="全部" style="width: 100%">
                        <el-option label="收入" value="income" />
                        <el-option label="支出" value="expense" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item label="账户">
                      <el-select v-model="filters.account_id" @change="fetchTransactions" placeholder="全部账户" style="width: 100%">
                        <el-option
                          v-for="account in accounts"
                          :key="account.id"
                          :label="account.name"
                          :value="account.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item label="分类">
                      <el-select v-model="filters.category_id" @change="fetchTransactions" placeholder="全部分类" style="width: 100%">
                        <el-option
                          v-for="category in categories"
                          :key="category.id"
                          :label="category.name"
                          :value="category.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="6" :lg="4">
                    <el-form-item label="项目">
                      <el-select v-model="filters.project_id" @change="fetchTransactions" placeholder="全部项目" style="width: 100%">
                        <el-option
                          v-for="project in projects"
                          :key="project.id"
                          :label="project.name"
                          :value="project.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="24" :md="12" :lg="8">
                    <el-form-item label="日期范围">
                      <el-date-picker
                        v-model="dateRange"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期时间"
                        end-placeholder="结束日期时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        @change="handleDateRangeChange"
                        style="width: 100%"
                        :shortcuts="dateShortcuts"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <!-- 交易列表 -->
                <el-table
                  :data="transactions"
                  style="width: 100%"
                  :empty-text="transactions.length === 0 && !loading ? '暂无交易记录' : '加载中...'"
                >
                  <el-table-column prop="transaction_date" label="日期" width="120">
                    <template #default="{ row }">
                      {{ formatDate(row.transaction_date) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="金额" width="140">
                    <template #default="{ row }">
                      <span :class="['amount-cell', row.transaction_type]">
                        {{ row.transaction_type === "income" ? "+" : "-" }}¥{{ formatAmount(parseFloat(row.amount)) }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="transaction_type" label="类型" width="100">
                    <template #default="{ row }">
                      <el-tag :type="row.transaction_type === 'income' ? 'success' : 'danger'">
                        {{ row.transaction_type === 'income' ? '收入' : '支出' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="描述" min-width="150">
                    <template #default="{ row }">
                      <el-tooltip
                        :content="row.description || '无描述'"
                        placement="top"
                        :disabled="!row.description || row.description.length <= 5"
                      >
                        <span class="description-text">
                          {{ truncateDescription(row.description) }}
                        </span>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column prop="category_id" label="分类" min-width="120">
                    <template #default="{ row }">
                      <span v-if="row.category_id">
                        {{ getCategoryName(row.category_id) }}
                      </span>
                      <span v-else class="text-muted">无分类</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="account_id" label="账户" min-width="120">
                    <template #default="{ row }">
                      {{ getAccountName(row.account_id) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="project_id" label="项目" min-width="120">
                    <template #default="{ row }">
                      <span v-if="row.project_id">
                        {{ getProjectName(row.project_id) }}
                      </span>
                      <span v-else class="text-muted">无项目</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                      <el-button size="small" @click="editTransaction(row)" :icon="Edit" />
                      <el-button size="small" type="danger" @click="deleteTransaction(row)" :icon="Delete" />
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 空状态 -->
                <el-empty v-if="transactions.length === 0 && !loading" description="暂无交易记录">
                  <el-button type="primary" @click="showAddTransactionModal = true">
                    添加第一笔交易
                  </el-button>
                </el-empty>
          </div>
        </el-col>
      </el-row>
    </el-main>

    <!-- 添加交易模态框 -->
    <AddTransactionModal
      v-model:visible="showAddTransactionModal"
      :edit-data="editTransactionData"
      @close="handleTransactionModalClose"
      @success="handleAddTransactionSuccess"
    />

    <!-- 分类管理模态框 -->
    <CategoryManagementModal
      v-model:visible="showCategoryManagement"
      @close="handleCategoryManagementClose"
      @success="handleCategoryManagementSuccess"
    />

    <!-- 账户管理模态框 -->
    <AccountManagementModal
      v-model:visible="showAccountManagement"
      @close="handleAccountManagementClose"
      @success="handleAccountManagementSuccess"
    />

    <!-- 项目管理模态框 -->
    <ProjectManagementModal
      v-model:visible="showProjectManagement"
      @close="handleProjectManagementClose"
      @success="handleProjectManagementSuccess"
    />

    </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { useAccountingStore } from "@/stores/accounting";
import AddTransactionModal from "./AddTransactionModal.vue";
import CategoryManagementModal from "./CategoryManagementModal.vue";
import AccountManagementModal from "./AccountManagementModal.vue";
import ProjectManagementModal from "./ProjectManagementModal.vue";
// import DateRangePicker from "@/components/DateRangePicker.vue";
import { Plus, Edit, Delete, TrendCharts, Wallet, Document } from "@element-plus/icons-vue";
import type {
  TransactionResponse,
  TransactionListParams,
} from "@/types/accounting";

// 定义组件事件
defineEmits<{
  close: [];
}>();

// 使用 store
const accountingStore = useAccountingStore();

// 响应式状态
const loading = computed(() => accountingStore.loading);
const statistics = computed(() => accountingStore.statistics);

// 数据列表
const transactions = computed(() => accountingStore.transactions);
const categories = computed(() => accountingStore.categories);
const accounts = computed(() => accountingStore.accounts);
const projects = computed(() => accountingStore.projects);

// 筛选器
const filters = reactive<TransactionListParams>({
  transaction_type: undefined,
  account_id: undefined,
  category_id: undefined,
  project_id: undefined,
  start_date: undefined,
  end_date: undefined,
});

// 日期范围
const dateRange = ref<[string, string] | null>(null);
// currentQuickDate 已移除，使用日期选择器内置快捷选项

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近三月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
  {
    text: '最近一年',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
      return [start, end];
    },
  },
];

// 快速日期选项已移至日期选择器内
// const quickDateOptions = [
//   { key: 'today', label: '今天' },
//   { key: 'week', label: '最近一周' },
//   { key: 'month', label: '最近一月' },
//   { key: 'quarter', label: '最近三月' },
//   { key: 'year', label: '最近一年' },
// ];

// 模态框状态
const showAddTransactionModal = ref(false);
const showCategoryManagement = ref(false);
const showAccountManagement = ref(false);
const showProjectManagement = ref(false);

// 编辑数据状态
const editTransactionData = ref<TransactionResponse | null>(null);

// 统计数据计算属性
const stats = computed(() => [
  {
    title: "总收入",
    value: `¥${formatAmount(parseFloat(statistics.value.total_income))}`,
    type: "income",
    icon: TrendCharts,
  },
  {
    title: "总支出",
    value: `¥${formatAmount(parseFloat(statistics.value.total_expense))}`,
    type: "expense",
    icon: TrendCharts,
  },
  {
    title: "结余",
    value: `¥${formatAmount(parseFloat(statistics.value.net_income))}`,
    type: "balance",
    icon: Wallet,
  },
  {
    title: "交易笔数",
    value: statistics.value.transaction_count.toString(),
    type: "transactions",
    icon: Document,
  },
]);


// 获取统计数据
const fetchStatistics = async () => {
  try {
    await accountingStore.fetchStatistics();
  } catch (error) {
    console.error("获取统计数据失败:", error);
  }
};

// 获取交易记录
const fetchTransactions = async () => {
  try {
    await accountingStore.fetchTransactions(filters);
  } catch (error) {
    console.error("获取交易记录失败:", error);
  }
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    await accountingStore.fetchCategories();
  } catch (error) {
    console.error("获取分类列表失败:", error);
  }
};

// 获取账户列表
const fetchAccounts = async () => {
  try {
    await accountingStore.fetchAccounts();
  } catch (error) {
    console.error("获取账户列表失败:", error);
  }
};

// 获取项目列表
const fetchProjects = async () => {
  try {
    await accountingStore.fetchProjects();
  } catch (error) {
    console.error("获取项目列表失败:", error);
  }
};

// 截断描述文本
const truncateDescription = (description: string | null | undefined): string => {
  if (!description) return '无描述';
  return description.length > 5 ? description.substring(0, 5) + '...' : description;
};

// 格式化金额
const formatAmount = (amount: number): string => {
  return amount.toFixed(2);
};

// 格式化日期
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString("zh-CN");
};

// 获取分类名称
const getCategoryName = (categoryId: number): string => {
  const category = categories.value.find(c => c.id === categoryId);
  return category ? category.name : '未知分类';
};

// 获取账户名称
const getAccountName = (accountId: number): string => {
  const account = accounts.value.find(a => a.id === accountId);
  return account ? account.name : '未知账户';
};

// 获取项目名称
const getProjectName = (projectId: number): string => {
  const project = projects.value.find(p => p.id === projectId);
  return project ? project.name : '未知项目';
};

// 编辑交易
const editTransaction = (transaction: TransactionResponse) => {
  editTransactionData.value = transaction;
  showAddTransactionModal.value = true;
};

// 删除交易
const deleteTransaction = async (transaction: TransactionResponse) => {
  if (!confirm("确定要删除这笔交易吗？")) {
    return;
  }

  try {
    await accountingStore.deleteTransaction(transaction.id);
  } catch (error) {
    console.error("删除交易失败:", error);
    alert("删除交易失败，请重试");
  }
};

// 处理模态框成功事件
const handleAddTransactionSuccess = async () => {
  editTransactionData.value = null;
  await fetchTransactions();
  await fetchStatistics();
};


// 处理日期范围变化
const handleDateRangeChange = (value: [string, string] | null) => {
  if (value && value.length === 2) {
    filters.start_date = value[0];
    filters.end_date = value[1];
  } else {
    filters.start_date = undefined;
    filters.end_date = undefined;
  }
  fetchTransactions();
};

// selectQuickDate 函数已移除，使用日期选择器内置快捷选项


const handleTransactionModalClose = () => {
  editTransactionData.value = null;
  showAddTransactionModal.value = false;
};

// 分类管理处理函数
const handleCategoryManagementClose = () => {
  showCategoryManagement.value = false;
};

const handleCategoryManagementSuccess = async () => {
  showCategoryManagement.value = false;
  await fetchCategories();
};

// 账户管理处理函数
const handleAccountManagementClose = () => {
  showAccountManagement.value = false;
};

const handleAccountManagementSuccess = async () => {
  showAccountManagement.value = false;
  await fetchAccounts();
};

// 项目管理处理函数
const handleProjectManagementClose = () => {
  showProjectManagement.value = false;
};

const handleProjectManagementSuccess = async () => {
  showProjectManagement.value = false;
  await fetchProjects();
};

// 处理键盘事件
const handleKeyDown = (event: KeyboardEvent) => {
  // 如果按下了ESC键且有模态框打开
  if (event.key === "Escape" && showAddTransactionModal.value) {
    // 阻止事件冒泡，避免关闭整个应用窗口
    event.stopPropagation();
    event.preventDefault();

    // 关闭模态框
    showAddTransactionModal.value = false;
  }
};

// 初始化
onMounted(async () => {
  await accountingStore.initialize();
  await fetchTransactions();
  // 添加键盘事件监听器
  document.addEventListener("keydown", handleKeyDown);
});

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener("keydown", handleKeyDown);
});
</script>

<style lang="scss" scoped>
.accounting-management {
  height: 100%;
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  overflow: hidden;
}

.accounting-main {
  padding: 24px;
  overflow-y: auto;
  height: 100%;
}

// 统计卡片
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  transition: all 0.3s ease;
  border: 1px solid var(--el-border-color);

  &:hover {
    border-color: var(--el-border-color-light);
    box-shadow: var(--el-box-shadow-light);
  }

  &.compact {
    .stat-icon {
      width: 36px;
      height: 36px;
    }
    
    .stat-title {
      font-size: 12px;
    }
    
    .stat-value {
      font-size: 16px;
    }
  }
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--el-border-radius-small);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;

  &.income {
    background: var(--el-color-success);
  }

  &.expense {
    background: var(--el-color-danger);
  }

  &.balance {
    background: var(--el-color-primary);
  }

  &.transactions {
    background: var(--el-color-info);
  }
}

.stat-icon-col {
  display: flex;
  justify-content: center;
  align-items: center;
}

.stat-content {
  text-align: left;
}

.stat-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin: 0 0 8px 0;
  font-weight: 400;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  margin: 0;

  &.income {
    color: var(--el-color-success);
  }

  &.expense {
    color: var(--el-color-danger);
  }

  &.balance {
    color: var(--el-color-primary);
  }

  &.transactions {
    color: var(--el-color-info);
  }
}

// 主要内容区域
.main-content {
  margin-bottom: 24px;
}

.content-area {
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  padding: 24px;
  min-height: 400px;
}

.section-header {
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
}

// 筛选器
.filters {
  margin-bottom: 24px;
  padding: 16px;
  background: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);

  // Enhanced dropdown styling for filters
  :deep(.el-select) {
    .el-input__wrapper {
      border-radius: var(--el-border-radius-small);
      transition: all 0.3s ease;
      
      &:hover {
        border-color: var(--el-border-color-light);
      }
      
      &.is-focus {
        border-color: var(--el-color-primary);
        box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
      }
    }
    
    .el-input__inner {
      font-size: 14px;
      color: var(--el-text-color-primary);
    }
  }

  :deep(.el-select-dropdown) {
    border-radius: var(--el-border-radius-base);
    border: 1px solid var(--el-border-color);
    box-shadow: var(--el-box-shadow-light);
    
    .el-select-dropdown__item {
      font-size: 14px;
      padding: 8px 16px;
      transition: all 0.2s ease;
      
      &:hover {
        background: var(--el-bg-color-overlay);
        color: var(--el-color-primary);
      }
      
      &.selected {
        color: var(--el-color-primary);
        font-weight: 500;
      }
    }
  }
}

// 交易表格样式
.income {
  color: var(--el-color-success);
  font-weight: 600;
}

.expense {
  color: var(--el-color-danger);
  font-weight: 600;
}

.amount-cell {
  font-weight: 700;
  font-size: 16px;
  
  &.income {
    color: var(--el-color-success);
  }
  
  &.expense {
    color: var(--el-color-danger);
  }
}

.text-muted {
  color: var(--el-text-color-placeholder);
  font-size: 12px;
}

.description-text {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

// 卡片样式
.category-card,
.account-card,
.project-card {
  transition: all 0.3s ease;
  height: 100%;

  &:hover {
    border-color: var(--el-border-color-light);
    box-shadow: var(--el-box-shadow-light);
  }
}

.category-icon,
.account-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--el-border-radius-small);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.category-info,
.account-info {
  margin-left: 16px;
}

.category-name,
.account-name,
.project-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
}

.account-type {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin: 0 0 4px 0;
}

.account-balance {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
}

.project-description {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin: 0 0 8px 0;
}

.project-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.category-actions,
.account-actions,
.project-actions {
  display: flex;
  align-items: center;
  gap: 4px;
}

// 快速日期按钮已移除，使用日期选择器内置快捷选项
// .quick-date-buttons {
//   display: flex;
//   flex-wrap: wrap;
//   gap: 6px;
  
//   .el-button {
//     flex: 1;
//     min-width: 60px;
//     padding: 4px 8px;
//     font-size: 12px;
//   }
// }

// 响应式设计
@media (max-width: 1200px) {
  .stats-section {
    .el-col {
      margin-bottom: 16px;
    }
  }
}

@media (max-width: 992px) {
  .filters {
    .el-col {
      margin-bottom: 16px;
    }
  }
}

@media (max-width: 768px) {
  .accounting-main {
    padding: 16px;
  }

  .stats-section {
    margin-bottom: 16px;
    
    .el-col {
      margin-bottom: 12px;
    }
  }

  .filters {
    padding: 12px;
    margin-bottom: 16px;
    
    .el-col {
      margin-bottom: 12px;
    }
  }

  .content-area {
    padding: 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 8px;
    
    .el-button {
      width: 100%;
      justify-content: flex-start;
      
      .button-text {
        display: inline;
      }
    }
    
    .primary-action {
      order: -1;
    }
  }

  .section-header {
    margin-bottom: 16px;
  }

  // 表格响应式
  :deep(.el-table) {
    font-size: 12px;
    
    .el-table__cell {
      padding: 8px 0;
    }
    
    .el-button {
      padding: 4px 8px;
      font-size: 12px;
    }
  }
}

@media (max-width: 480px) {
  .accounting-main {
    padding: 12px;
  }

  .stats-section {
    margin-bottom: 12px;
  }

  .content-area {
    padding: 12px;
  }

  .filters {
    padding: 8px;
  }

  .stat-card {
    .stat-title {
      font-size: 11px;
    }
    
    .stat-value {
      font-size: 14px;
    }
    
    .stat-icon {
      width: 32px;
      height: 32px;
      
      .el-icon {
        font-size: 16px;
      }
    }
  }

  // 表格横向滚动
  .content-area {
    overflow-x: auto;
    
    :deep(.el-table) {
      min-width: 600px;
    }
  }
}

@media (max-height: 600px) {
  .accounting-main {
    padding: 8px;
  }

  .stats-section {
    margin-bottom: 8px;
  }

  .content-area {
    padding: 8px;
  }

  .filters {
    padding: 8px;
    margin-bottom: 8px;
  }
}
</style>
